/**
 * Service
 */

import { Injectable } from '@angular/core';
import { HEROES } from './mock-heroes';
import { Hero } from './app.hero';

import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HeroService {

    constructor(private http: Http) {
    }

    getHeroes(): Promise<Hero[]> {
        //return HEROES;
        //return Promise.resolve(HEROES);
        // return new Promise((resolve, reject) => {
        //     setTimeout(() => {
        //         resolve(HEROES);
        //     }, 1);
        // });
        return this.http.get("http://localhost:3333/hero/heroes")
            .toPromise()
            .then((response) => {
                return response.json() as Hero[];
            })
            .catch((err) => {
                console.error(err);
            });
    };
    getHero(id): Promise<Hero> {
        // return new Promise((resolve, reject) => {
        //     resolve(HEROES.find(function (val: Hero, idx: number, obj: Hero[]) {
        //         return val.id === id;
        //     }));
        // });
        return this.http.get("http://localhost:3333/hero/get/" + id)
            .toPromise()
            .then((response) => {
                return response.json() as Hero;
            })
            .catch((err) => {
                console.error(err);
            });
    }

    addHero(name): Promise<string> {
        return this.http.get("http://localhost:3333/hero/add/" + name)
            .toPromise()
            .then((response) => {
                return response.json() as string;
            })
            .catch((err) => {
                console.error(err);
            });
    }

    removeHero(id): Promise<string> {
        return this.http.get("http://localhost:3333/hero/remove/" + id)
            .toPromise()
            .then((response) => {
                return response.json() as string;
            })
            .catch((err) => {
                console.error(err);
            });
    }

}
